<template>
 <div class="processDetail">
  <back-page></back-page>
  <van-tabs v-model="activeDetail" :swipeable="true"  @click="handleClick">
    <van-tab title="基本信息" >
      <div class="processbox">
        <div v-for="(item, index) in runningTasks" :key="index" v-if="details != 'details'">
          <div class="approvalTitle">
            审批任务【{{ item.name }}】
          </div>
          <van-form :ref="'form' + index" :model="auditForms[index]" :rules="auditRule" @submit="submit">
              <van-field name='processName' v-model="processInstance.name" label="流程名：" v-if="processInstance && processInstance.name"/>
              <van-field label="流程发起人：" v-if="processInstance && processInstance.startUser">
                <template #input>
                    {{processInstance.startUser.nickname}}
                    <el-tag type="info" size="mini">{{ processInstance.startUser.deptName }}</el-tag>
                  </template>
              </van-field>
              <van-field
                v-model="auditForms[index].reason" 
                rows="4"
                autosize
                label="审批建议："
                name="reason"
                type="textarea"
                :rules="[{ required: true, message: '审批建议不能为空' }]"
                placeholder="请输入"
              />
              <van-field name="isCC" label="抄送：">
                <template #input>
                  <van-switch  v-model="checked" size="20" @change="handleCheckedChange"/>
                </template>
              </van-field>
              <van-field name="cc" label="抄送给：" v-if="checked">
                <template #input>
                 <div class="selectUser">
                    <div class="">
                        <van-tag type="primary"
                            v-for="tag in tagsList"
                            :key="tag.id">
                            {{ tag.username }}
                        </van-tag>
                    </div>
                    <span @click="onRecipient" class="selectBtn">请选择 ></span>
                 </div>
                </template>
              </van-field>
              <van-field name="uploader" label="附件信息：">
                <template #input >
                  <el-upload
                    class="upload-demo"
                    :before-upload="beforeUpload"
                    :on-success="uploadSuccess"
                    :limit="5"
                    ref="uploadFile"
                    :multiple="true"
                    :on-exceed="onExceed"
                    :headers="{ 'Authorization': 'Bearer ' + localStorageTemp, 'tenant-id': tenantId }"
                    :show-file-list="false"
                    :action="loadAction"
                  >
                    <el-button  type="primary" size="small" v-loading="uploadLoading">文件上传</el-button>
                    <div slot="tip" class="el-upload__tip">
                      <span>提示：最多上传5个文件，单个文件不超过1M。</span>
                      <div v-if="fileDocList.length > 0" class="showFileDoc" style="padding-top:5px">
                        <div class="lineFilecss" style="font-size:14px" v-for="(item, idx) in fileDocList" :key="idx">
                          <i class="el-icon-document"></i>
                          <span class="fileTextCss" :title="item.name" @click="viewFile(item)">{{item.name}}</span>
                          <span><i class="el-icon-download fileIcon" @click="downloadFileFunc(item)"></i></span>
                          <span><i class="el-icon-delete fileIcon" @click="deleteFile(item, idx)"></i></span>
                        </div>
                      </div>
                    </div>
                  </el-upload>
                  <el-upload
                    class="upload-demo"
                    style="margin-top: 20px;"
                    ref="upload"
                    :action="uploadImgUrl"
                    accept=".jpg, .png, .jpeg"
                    :limit="3"
                    :on-exceed="handleExceed"
                    :headers="headersImg"
                    :before-upload="handleBeforeUpload"
                    :file-list="fileList"
                    :on-remove="handleRemove"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    >
                    <el-button  type="primary" size="small" v-loading="uploadImgLoading">图片上传</el-button>
                    <div slot="tip" class="el-upload__tip">
                      <span>提示：最多上传3张图片，请上传jpg、jpeg、png格式图片，单张图片不超过1M</span>
                    </div>
                  </el-upload>
                </template>
              </van-field>
          </van-form>
      </div>
      <div>
        <div class="approvalTitle">
          申请信息【{{ processInstance.name }}】
        </div>
        <div >
          <parser :key="new Date().getTime()" :form-conf="detailForm" @submit="submitForm" :status='status'/>
        </div>
      </div>
      </div>
      <div v-if="details != 'details'" style="height:45px;">
        <div v-for="(item, index) in runningTasks" :key="index" class="processbtnbox">
        <div class="butList">
            <el-button size="small"  v-if="buttonList.filter((_) => _.value == 'flow_agree') && buttonList.filter((_) => _.value == 'flow_agree').length == 1"  type="success"  @click="handleAudit(item,'success')">
              {{buttonList.filter((_) => _.value == 'flow_agree') && buttonList.filter((_) => _.value == 'flow_agree')[0].label}}
            </el-button>
            <el-button size="small" v-if="buttonList.filter((_) => _.value == 'flow_not_agree') && buttonList.filter((_) => _.value == 'flow_not_agree').length == 1"  type="danger" @click="handleAudit(item, 'danger')">
              {{buttonList.filter((_) => _.value == 'flow_not_agree') && buttonList.filter((_) => _.value == 'flow_not_agree')[0].label}}
            </el-button>
            <el-button size="small" v-if="buttonList.filter((_) => _.value == 'flow_translate') && buttonList.filter((_) => _.value == 'flow_translate').length == 1"  type="primary"  @click="handleAudit(item,'translate')">
              {{buttonList.filter((_) => _.value == 'flow_translate') && buttonList.filter((_) => _.value == 'flow_translate')[0].label}}
            </el-button>
            <el-button size="small" v-if="buttonList.filter((_) => _.value == 'flow_reject') && buttonList.filter((_) => _.value == 'flow_reject').length == 1"  type="warning"  @click="handleAudit(item,'reject')">
              {{buttonList.filter((_) => _.value == 'flow_reject') && buttonList.filter((_) => _.value == 'flow_reject')[0].label}}
            </el-button>
          </div>
      </div>
      </div>
    </van-tab>
    <van-tab title="流转记录" v-loading="tasksLoad">
      <el-col >
        <div class="block">
          <el-timeline>
            <el-timeline-item v-for="(item, index) in tasks" :key="index"
                              :icon="getTimelineItemIcon(item)" :type="getTimelineItemType(item)">
              <div class="taskStyle">
                <p :class="item.result == 1 ?  'taskNameTime': 'taskName'">任务：{{ item.name }}</p>
                <span class="endTime">{{ parseTime(item.endTime) }}</span>
              </div>
              <div class="mobileAss">
                <span>审批人：{{ item.assigneeUser.nickname }}</span>
                <el-tag type="info" size="mini" v-if="item.assigneeUser.deptName">{{ item.assigneeUser.deptName }}</el-tag>
              </div>
              <div style="margin-top: 10px;"  v-if="item.reason">
                <span>审批意见：{{item.reason}}</span>
              </div>
              <div style="margin-top: 10px"  v-if="item.fileList&&item.fileList.length > 0 || item.imageList&&item.imageList.length > 0">
                <span style="margin-bottom: 5px">附加信息：</span>
                <div class="lineFilecss" v-for="(item, idx) in item.fileList" :key="idx">
                    <i class="el-icon-document"></i>
                    <span class="fileTextCss" :title="item.name" @click="viewFile(item)">{{item.name}}</span>
                    <!-- <span><i class="el-icon-download fileIcon" @click="downloadFileFunc(item)"></i></span> -->
                    <el-button type="text"  @click="downloadFileFunc(item)">下载</el-button>
                </div>
                <div>
                  <div v-for="(item, index) in item.imageList" :key="index" style="width:60%;margin-right: 20px">
                    <img :src="item.url" style="width:100%"/>
                  </div>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-col>
    </van-tab>
    <van-tab title="流程跟踪"  v-loading="processInstanceLoading">
       <my-process-viewer key="designer" v-model="bpmnXML" v-bind="bpmnControlForm" :activityData="activityList"
              :processInstanceData="processInstance" :taskData="tasks" />
    </van-tab>
  </van-tabs>
    <!-- 对话框(转派审批人) -->
  <van-dialog  v-model="updateAssignee.open" title="转派审批人" show-cancel-button :beforeClose="chargeBtn" z-index="200">
    <el-form ref="updateAssigneeForm" :model="updateAssignee.form" :rules="updateAssignee.rules" label-width="90px">
      <el-form-item label="新审批人" prop="assigneeUserId">
        <el-select v-model="updateAssignee.form.assigneeUserId" clearable style="width: 100%" popper-class="select">
          <el-option v-for="item in userOptions" :key="parseInt(item.id)" :label="item.nickname" :value="parseInt(item.id)"/>
        </el-select>
      </el-form-item>
    </el-form>
  </van-dialog>

  <!-- 驳回 -->
  <van-dialog title="驳回" v-model="returnBtn.open" show-cancel-button :beforeClose="rejectBtn" z-index="200">
    <el-form ref="returnBtnForm" :model="returnBtn.form"  label-width="90px" :rules="returnBtn.rules">
      <el-form-item label="驳回方式"  prop="rejection">
        <el-radio-group v-model="returnBtn.form.rejection" @change="changeRejection">
          <el-radio :label="1" >驳回发起人</el-radio>
          <el-radio :label="2">驳回上一步</el-radio>
          <el-radio :label="3">驳回指定节点</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="返回方式" prop="returnMethod">
        <el-radio-group v-model="returnBtn.form.returnMethod">
          <el-radio :label="1">按流程图执行</el-radio>
          <!-- <el-radio :label="2" v-if="returnBtn.form.rejection !=3">回到本节点</el-radio> -->
        </el-radio-group>
      </el-form-item>
      <el-form-item label="驳回节点" prop="distFlowElementId" v-if="returnBtn.form.rejection==3">
        <el-select v-model="returnBtn.form.distFlowElementId" clearable style="width: 100%">
          <el-option v-for="item in nodeList" :key="item.nodeId" :label="item.nodeName" :value="item.nodeId" />
        </el-select>
      </el-form-item>
        <!-- <el-form-item label="审批建议" prop="message">
          <el-input type="textarea" v-model="returnBtn.form.message"></el-input>
      </el-form-item> -->
    </el-form>
    <!-- <div slot="footer" class="dialog-footer">
      <el-button @click="cancelReturnBtnForm">取 消</el-button>
      <el-button type="primary" @click="submitReturnBtnForm">驳 回</el-button>
    </div> -->
  </van-dialog>
   <mobileSelectUser @userInfo="info" :tagsList="tagsList" v-if="openRecipient" @closeRecipient="closeRecipient"></mobileSelectUser>
 </div>
</template>

<script>
import {getProcessDefinitionBpmnXML} from "@/api/bpm/definition";
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import store from "@/store";
import {decodeFields} from "@/utils/formGenerator";
import Parser from '@/views/mobileCustom/components/parser.vue'
import {createProcessInstance, getProcessInstance} from "@/api/bpm/processInstance";
import {approveTask, getTaskListByProcessInstanceId, rejectTask, updateTaskAssignee,getNodeList,doBack,doBackDist} from "@/api/bpm/task";
import {listSimpleUsers} from "@/api/system/user";
import {getActivityList,getCarbonCopy} from "@/api/bpm/activity";
import { updata } from "@/api/custom/formPoster";
import mobileSelectUser from '@/components/selectUser/mobileSelectUser.vue'
// 下载插件
import { download } from '@/utils/index'
import { getAccessToken } from "@/utils/auth";
export default {
  components: {
    Parser,
    mobileSelectUser
  },
  data() {
    return {
      auditRule: {
        reason: [{ required: true, message: "审批建议不能为空", trigger: "blur" }],
      }, //审批建议规则
      fileList:[],
      uploader:[], //上传文件
      uploadLoading:false,//上传加载状态
      fileDocList: [],
      loadAction: '',
      localStorageTemp: '',
      tenantId: '',
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址,
      headersImg: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
      uploadImgLoading: false,
      editRow: '',
      openRecipient: false,
       // 转派审批人
      userOptions: [],
      task: '',
      type: '',
      auditForms: [],
      tagsList: [],
      buttonList: [],
      checked: false,
      activeDetail:0,
      // BPMN 数据
      bpmnXML: null,
      activityList: [],
      tasks: [],
      status: 'view',
      processInstanceLoading: true,
      processInstance: {},
      bpmnControlForm: {
        prefix: "activiti"
      },
       // 退回
      returnBtn: {
        open: false,
        form: {
          rejection: 1,
          returnMethod: 1,
          distFlowElementId: undefined,
          message: undefined
        },
        rules: {
          rejection: [{ required: true,  message: "驳回方式不能为空",trigger: "blur"}],
          returnMethod: [{ required: true, message: "返回方式不能为空", trigger: "blur"}],
          distFlowElementId: [{ required: true,  message: "节点不能为空", trigger: "blur"}],
          message: [{ required: true,  message: "审批建议不能为空", trigger: "blur"}],
        }
      },
       // 流程表单详情
      detailForm: {
        fields: []
      },
      updateAssignee: {
        open: false,
        form: {
          assigneeUserId: undefined,
        },
        rules: {
          assigneeUserId: [{ required: true, message: "新审批人不能为空", trigger: "change" }],
        }
      },
    };
  },
  created() {
    this.api = process.env.VUE_APP_BASE_API;
    this.loadAction = `${this.api}/admin-api/infra/file/upload`;
    this.localStorageTemp = window.localStorage.getItem('ACCESS_TOKEN');
    this.tenantId = window.localStorage.getItem('TENANT_ID')
    this.details = this.$route.query.details
    this.editRow = this.$route.query.edit && JSON.parse(this.$route.query.edit)
    this.id = this.$route.query.id;
    if (!this.id) {
      this.$message.error('未传递 id 参数，无法查看流程信息');
      return;
    }
    this.getDetail();

    //获得用户列表
    this.userOptions = [];
    listSimpleUsers().then(response => {
      this.userOptions.push(...response.data);
    });

  },
  methods:{
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
    },
    // 图片删除
    handleRemove(file, fileList) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if(findex > -1) {
        this.fileList.splice(findex, 1);
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$message.warning('上传图片不能超过3个')
    },
    // 图片上传前回调
    handleBeforeUpload(file) {
        const size = file.size / 1024 / 1024
        if (size > 50) {
            this.$message.warning('图片最大不超过1M')
            return false
        }
        this.uploadImgLoading = true
    },
    // 图片上传
    handleUploadSuccess(res,file) {
      if(res.code == 0) {
        this.fileList.push({name: file.name, url: res.data})
      }else{
        this.$modal.msgError("上传图片失败，请重试");
      }
      this.uploadImgLoading = false
    },
    viewFile (item) {
        const nameSplitList = item.name.split('.')
        const type = nameSplitList[nameSplitList.length - 1]
        if (['jpeg', 'jpg', 'png'].includes(type)) {
            window.open(item.url, '_blank')
        } else {
            this.$message.warning('当前文件不支持预览')
        }
        // 代码注释
        //  else if (['docx', 'doc', 'xlsx', 'xls', 'pdf'].includes(type)) {
        //     this.$message.warning('当前文件不支持预览')
        //     // let newFileUrl = encodeURIComponent(item.url)
        //     // newFileUrl = 'http://view.xdocin.com/xdoc?_xdoc=' + newFileUrl
        //     // window.open(newFileUrl, '_blank')
        // } else if (type === 'pdf') {
        //     this.$message.warning('当前文件不支持预览')
        // }
    },
    downloadFileFunc (item) {
        download(item.url, item.name)
    },
    deleteFile (item, idx) {
        this.fileDocList.splice(idx, 1)
    },
    onExceed (files, fileList) {
        if (this.fileDocList.length === 5) {
            this.$message.warning('当前限制5个文件')
            // this.$refs.uploadFile.abort()
            return false
        }
    },
    // 上传前钩子判断
    beforeUpload (file) {
      const size = file.size / 1024 / 1024
      if (size > 10) {
        this.$message.warning('文件最大不超过1M')
        return false
      }
      this.uploadLoading = true
    },
    // 上传成功钩子事件
    uploadSuccess (response, file, fileList) {
      if (response.code === 0) {
        this.fileDocList.push({name: file.name, url: response.data})
      }else{
        this.$modal.msgError("上传文件失败，请重试");
      }
      this.uploadLoading = false
    },

      /** 提交按钮 */
    submitForm(params) {
      if (!params) {
        return;
      }
        // 提交表单，创建流程
      const variables = params;
      if(this.editRow){  // 我的任务编辑
        const formJsonData = JSON.parse(this.editRow.formJsonData)
        formJsonData.data?.map((item) => {
          item.value =  params[item.name]
          item.type =  item.format
        })
        const data = {
          ...formJsonData,
          dataId: this.editRow.formId,
        }
        updata(data).then((res) => {
          this.$message.success('修改成功')
            // 关闭当前窗口
          this.$tab.closeOpenPage();
          this.$router.go(-1);
        })
      }else{
          // 设置表单禁用
        // const conf = params.conf;
        this.detailForm.disabled = true; // 表单禁用
        this.status = 'view' // 按钮隐藏
        // conf.formBtns = false; // 按钮隐藏
        createProcessInstance({
          processDefinitionId: this.selectProcessInstance.id,
          variables: variables
        }).then(response => {
          this.$modal.msgSuccess("发起流程成功");
          // 关闭当前窗口
          this.$tab.closeOpenPage();
          this.$router.go(-1);
        }).catch(() => {
          this.detailForm.disabled = false; // 表单开启
          // conf.formBtns = true; // 按钮展示
          this.status = 'add' // 按钮展示
          this.detailForm.btnConfig = [{ label: '确定', text: '提交', click: 'submit', checked: true, type: 'default' }] // 按钮展示
        })
      }
    },
    changeRejection(val) { // 驳回指定节点 -- 返回方式只有按流程图执行
      if(val == 3){
        this.returnBtn.form.returnMethod = 1
      }
    },
    closeRecipient() {
      this.openRecipient = false
    },
    onRecipient() {
      this.openRecipient = true
    },
    info(data) {
      this.tagsList = data 
    },
    handleCheckedChange(val) { // 是否抄送  -- false  清空 tagsList
      if(!val){
        this.tagsList = []
      }
    },
    handleClick(name,title) {
      if (name == 2) {
        this.getDetail();
      }
    },

    //驳回操作
    rejectBtn(action,done){ //驳回
      if(action == 'confirm'){ //确认
        this.$refs['returnBtnForm'].validate(valid => {
          if (!valid) {
            return;
          }
            //抄送
          let arr = []
          this.tagsList && this.tagsList.map((_) => {
              arr.push(_.id)
          })
          const copyData = {
            taskId: this.returnBtn.form.id,
            processInstanceId: this.processInstance.id,
            userIds: arr,
          }
          if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
            getCarbonCopy(copyData).then((res) =>{ })
          }
          if(this.returnBtn.form.rejection == 3){ // 驳回到指定节点
            const data = {
              reason: this.reason,
              imageList: this.fileList, //图片附件
              fileList: this.fileDocList,   //文件附件
              // processInstanceId: this.processInstance.id,
              type: "BH", // 驳回的方式
              distFlowElementId: this.returnBtn.form.distFlowElementId,
              message: this.returnBtn.form.message,
              userId: this.userId, // 审批用户的id
              taskId: this.returnBtn.form.id   // 任务id
            }
            doBack(data).then((res) => {
              this.$modal.msgSuccess("驳回成功！");
              this.tagsList = []
              this.fileList = []
              this.fileDocList = []
              this.checked = false
              this.returnBtn.open = false;
              this.getDetail(); // 获得最新详情
            })
          }else{ // 驳回发起人，驳回上一步
            const data = {
              reason: this.reason,
              imageList: this.fileList, //图片附件
              fileList: this.fileDocList,   //文件附件
              position: this.returnBtn.form.rejection == 1 ? 'start': 'last',
              type: "BH", // 驳回的方式
              distFlowElementId: this.returnBtn.form.distFlowElementId,
              message: this.returnBtn.form.message,
              userId: this.userId, // 审批用户的id
              taskId: this.returnBtn.form.id   // 任务id
            }
            doBackDist(data).then((res) => {
              this.$modal.msgSuccess("驳回成功！");
              this.tagsList = []
              this.fileList = []
              this.fileDocList = []
              this.checked = false
              this.returnBtn.open = false;
              this.getDetail(); // 获得最新详情
            })
          }
        });
      }else if(action == 'cancel'){
        this.returnBtn.open = false;
        this.resetReturnBtnForm();
        done()
      }
    },

    //转派操作
    chargeBtn(action,done) {
      if(action == 'confirm'){ //确认
        this.$refs['updateAssigneeForm'].validate(valid => {
          if (!valid) {
            return;
          }
          //抄送
          let arr = []
          this.tagsList && this.tagsList.map((_) => {
              arr.push(_.id)
          })
          const copyData = {
            taskId: this.updateAssignee.form.id,
            processInstanceId: this.processInstance.id,
            userIds: arr,
          }
          const data = {
            ...this.updateAssignee.form,
            reason: this.reason,
            imageList: this.fileList, //图片附件
            fileList: this.fileDocList   //文件附件
          }
          if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
            getCarbonCopy(copyData).then((res) =>{ })
          }
          updateTaskAssignee(data).then(response => {
            this.$modal.msgSuccess("转派任务成功！");
            done()
            this.tagsList = []
            this.fileList = []
            this.fileDocList = []
            this.checked = false
            this.updateAssignee.open = false;
            this.getDetail(); // 获得最新详情
          });
        });
      }else if(action == 'cancel'){ /** 取消转派审批人 */
        this.updateAssignee.open = false;
        this.resetUpdateAssigneeForm();
        done()
      }
    },
     /** 获得流程实例 */
    getDetail() {
      // 获得流程实例相关
      this.processInstanceLoading = true;
      getProcessInstance(this.id).then(response => {
        if (!response.data) {
          this.$message.error('查询不到流程信息！');
          return;
        }
        // 设置流程信息
        this.processInstance = response.data;
        // 设置表单信息
        if(this.editRow){ //编辑
            this.status = 'add'
            this.detailForm = {
              ...JSON.parse(this.processInstance.processDefinition.formConf),
              disabled: this.editRow ? false : true, // 表单禁用
              btnConfig: [{ label: '确定', text: '提交', click: 'submit', checked: true, type: 'default' }], // 按钮隐藏
              fields: decodeFields(this.processInstance.processDefinition.formFields)
          }
        }else{ //查看
          this.status = 'view'
          this.detailForm = {
            ...JSON.parse(this.processInstance.processDefinition.formConf),
            disabled: this.editRow ? false : true, // 表单禁用
            fields: decodeFields(this.processInstance.processDefinition.formFields)
          }
        }
          // 设置表单的值
          this.detailForm.fields.forEach(item => {
            // let  val = this.processInstance.formVariables[item.__vModel__]
            // item.__config__.defaultValue = val
            this.getTagIcons(item)
          });
        // }
        // 加载流程图
        getProcessDefinitionBpmnXML(this.processInstance.processDefinition.id,this.processInstance.id).then(response => {
          this.bpmnXML = response.data.bpmnXml
          this.buttonList = response.data.bpmnButton?.button
          this.carbonFlag = response.data.bpmnButton?.carbon?.isChecked //是否抄送
        });


        // 加载活动列表
        getActivityList({
          processInstanceId: this.processInstance.id
        }).then(response => {
          this.activityList = response.data;
        });

        // 取消加载中
        this.processInstanceLoading = false;
      });

      // 获得流程任务列表（审批记录）
      this.tasksLoad = true;
      this.runningTasks = [];
      this.auditForms = [];
      getTaskListByProcessInstanceId(this.id).then(response => {
        // 审批记录
        this.tasks = response.data;
        // 排序，将未完成的排在前面，已完成的排在后面；
        this.tasks.sort((a, b) => {
          // 有已完成的情况，按照完成时间倒序
          if (a.endTime && b.endTime) {
            return b.endTime - a.endTime;
          } else if (a.endTime) {
            return 1;
          } else if (b.endTime) {
            return -1;
            // 都是未完成，按照创建时间倒序
          } else {
            return b.createTime - a.createTime;
          }
        });

        // 需要审核的记录
        const userId = store.getters.userId;
        this.userId = userId
        this.tasks.forEach(task => {
          if (task.result !== 1) { // 只有待处理才需要
            return;
          }
          if (!task.assigneeUser || task.assigneeUser.id !== userId) { // 自己不是处理人
            return;
          }
          this.runningTasks.push({...task});
          this.auditForms.push({
            reason: ''
          })
        });

        // 取消加载中
        this.tasksLoad = false;
      });
    },
    getTagIcons(data) {
      if(data.__config__.tag === 'el-tabs' || data.__config__.tag === 'Steps'){
        data.__config__.children.map((c) => {
          if(c.__config__.tagIcon == 'row'){
            c.__config__.children.map((m) => {
              this.getTagIcons(m)
            })
          }
        })
      }else{
        let tag = data.__config__.tagIcon
        let val = this.processInstance.formVariables[data.__vModel__]
        // console.log(val)
        if(tag === 'cascader' || tag === 'checkbox' ){  //级联
              if (Array.isArray(val)) {
                  val = val.map((item) => {
                    return Number(item)
                  });
              } else {
                  val = val.split(',').map((item) => {
                    return Number(item)
                  });
              }
            }
            else if (tag === 'time-range' || tag === 'date-range'){
                val = val.split(',')
            }
            else  if (tag === 'radio' || tag === 'select') {
                 val = Number(val)
              }
             else if (tag === 'upload') {
                if (typeof val === 'string') {
                    val = JSON.parse(val)
                }
              }
           else if (tag === 'switch') { 
             val = val === 'true' ? true : false
            }
            data.__config__.defaultValue = val
      }
    },
    getTimelineItemIcon(item) {
      if (item.result === 1) {
        return 'el-icon-time';
      }
      if (item.result === 2) {
        return 'el-icon-check';
      }
      if (item.result === 3) {
        return 'el-icon-close';
      }
      if (item.result === 4) {
        return 'el-icon-remove-outline';
      }
      return '';
    },
    getTimelineItemType(item) {
      if (item.result === 1) {
        return 'primary';
      }
      if (item.result === 2) {
        return 'success';
      }
      if (item.result === 3) {
        return 'danger';
      }
      if (item.result === 4) {
        return 'info';
      }
      return '';
    },
    submit(values){ // 通过不通过
         //抄送
        let arr = []
        this.tagsList && this.tagsList.map((_) => {
            arr.push(_.id)
        })
        const copyData = {
           taskId: this.task.id,
           processInstanceId: this.processInstance.id,
           userIds: arr,
        }
        if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
           getCarbonCopy(copyData).then((res) =>{ })
        }
        const data = {
          id: this.task.id,
          reason: values.reason,
          imageList:this.fileList, //图片附件
          fileList:this.fileDocList,//文件附件
        }
        if (this.type == 'success') { //审批通过
          approveTask(data).then(response => {
            this.tagsList = []
            this.fileList=[]
            this.fileDocList=[]
            this.checked = false
            this.$modal.msgSuccess("审批通过成功！");
            this.getDetail(); // 获得最新详情
          });
        } else if(this.type == 'danger'){ // 审批不通过
          rejectTask(data).then(response => {
            this.$modal.msgSuccess("审批不通过成功！");
            this.getDetail(); // 获得最新详情
          });
        }
        if(this.type == 'translate') {  /** 处理转派审批人 */
            if(this.checked && this.tagsList.length == 0){
                return;
              }
            this.reason = values.reason
            // 设置表单
            this.resetUpdateAssigneeForm();
            this.updateAssignee.form.id = this.task.id;
            // 设置为打开
            this.updateAssignee.open = true;
        }
        if(this.type == 'reject'){    /** 退回 */
          if(this.checked && this.tagsList.length == 0){
              return;
            }
            this.reason = values.reason
            // 设置表单
            this.resetReturnBtnForm();
            this.returnBtn.form.id = this.task.id;
            // 设置为打开
            this.returnBtn.open = true;
            getNodeList(this.task.id).then((res) => {
                this.nodeList = res.data;
            })
        }
        console.log(values) //values为表单中van-field的值
    },
     /** 处理审批通过和不通过的操作 */
    handleAudit(task,type) {
      const index = this.runningTasks.indexOf(task);
      this.tagsList.length > 0 ? this.showFlag = false : this.showFlag = true
      this.task = task
      this.type = type
      this.$refs['form' + index][0].submit()
    },
    /** 重置转派审批人 */
    resetUpdateAssigneeForm() {
      this.updateAssignee.form = {
        id: undefined,
        assigneeUserId: undefined,
      };
      this.resetForm("updateAssigneeForm");
    },
    /** 处理审批退回的操作 */
    handleDelegate(task) {
      this.$modal.msgError("暂不支持【委派】功能，可以使用【转派】替代！");
    },
      /** 重置退回 */
    resetReturnBtnForm() {
      this.returnBtn.form = {
        rejection: 1,
        returnMethod: 1,
        distFlowElementId: undefined,
        suggestion: undefined
      };
      this.resetForm("returnBtnForm");
    },
    cancelReturnBtnForm() {
      this.returnBtn.open = false;
      this.resetReturnBtnForm();
    },
    /* 驳回提交 */
    submitReturnBtnForm() {
      this.$refs['returnBtnForm'].validate(valid => {
        if (!valid) {
          return;
        }
           //抄送
        let arr = []
        this.tagsList && this.tagsList.map((_) => {
            arr.push(_.id)
        })
        const copyData = {
           taskId: this.returnBtn.form.id,
           processInstanceId: this.processInstance.id,
           userIds: arr,
        }
        if(this.checked){ // 勾选是否抄送 请求  getCarbonCopy
           getCarbonCopy(copyData).then((res) =>{ })
        }
        if(this.returnBtn.form.rejection == 3){ // 驳回到指定节点
           const data = {
            // processInstanceId: this.processInstance.id,
            reason:this.reason,
            imageList:this.fileList, //图片附件
            fileList:this.fileDocList,// 文件附件
            type: "BH", // 驳回的方式
            distFlowElementId: this.returnBtn.form.distFlowElementId,
            message: this.returnBtn.form.message,
            userId: this.userId, // 审批用户的id
            taskId: this.returnBtn.form.id   // 任务id
          }
          doBack(data).then((res) => {
            this.$modal.msgSuccess("驳回成功！");
            this.tagsList = []
            this.fileList = []
            this.fileDocList = []
            this.checked = false
            this.returnBtn.open = false;
            this.getDetail(); // 获得最新详情
          })
        }else{ // 驳回发起人，驳回上一步
          const data = {
            reason:this.reason,
            imageList:this.fileList, //图片附件
            fileList:this.fileDocList,// 文件附件
            position: this.returnBtn.form.rejection == 1 ? 'start': 'last',
            type: "BH", // 驳回的方式
            distFlowElementId: this.returnBtn.form.distFlowElementId,
            // message: this.returnBtn.form.message,
            userId: this.userId, // 审批用户的id
            taskId: this.returnBtn.form.id   // 任务id
          }
          doBackDist(data).then((res) => {
            this.$modal.msgSuccess("驳回成功！");
            this.tagsList = []
            this.fileList = []
            this.fileDocList = []
            this.checked = false
            this.returnBtn.open = false;
            this.getDetail(); // 获得最新详情
          })
        }
      });
    },
  }
};
</script>

<style lang="scss">
  .van-field__control--custom {
    display: block;
  }
</style>
<style lang="scss" scoped>
.van-tab__pane {
  height:100%;
}
.select{
    z-index: 99999999 !important;
}
.processDetail{
  height:100vh;
  .processbox{
    height:calc(100% - 52px);
    overflow-y: auto;
  }
  .processbtnbox{
    height:45px;
  }
  ::v-deep .van-tabs{
    height:calc(100% - 30px)
  }
  ::v-deep .van-tabs__content{
    height:calc(100% - 44px)
  }
  ::v-deep .van-dialog__content{
    margin-top: 20px;
    padding-right: 10px;
  }
  ::v-deep .van-field__label{
    margin-right: 0 !important;
  }
  ::v-deep .van-tabs__line{
    background-color: #1890FF;
  }
   ::v-deep .van-tab__text {
    font-size: 16px;
  }
  ::v-deep .van-tab--active .van-tab__text{
    color: #1890FF;
  }
  ::v-deep .van-tab__text{
    color: rgba(151,151,151,1);
  }
  .taskStyle{
    position: relative;
  }
  .endTime{
    font-size: 13px;
    color: rgba(0, 0, 0, 0.25);
    position: absolute;
    top: 0;
    right: 5px;
  }
  .taskName{
    font-size: 15px;
    color:rgba(24,144,255,1);
    font-weight: 500;
  }
  .taskNameTime{
    font-size: 15px;
    color:rgba(0,0,0,0.65);
    font-weight: 500;
  }
  .mobileAss{
    font-size: 13px;
  }
   ::v-deep .el-tag.el-tag--info{
      background-color: rgba(239,245,255,1);
      border-color: #e9e9eb;
      color: rgba(31,120,254,1);
      margin-left: 10px;
    }
  .approvalTitle{
    text-align: center;
    background-color: #F1F2F6;
    font-size: 16px;
    padding: 9px 0;
    color: rgba(0,0,0,0.65);
    position: relative;
    width: calc(100% + 40px);
    margin-left: -20px;
  }
  .butList{
    height: 100%;
    padding:15px 0;
    text-align: center;
    width: 100%;
    box-sizing: border-box;
  }
  .selectUser{
    position: relative;
    width: 100%;
    div:nth-child(1){
      display: inline-block;
    }
    span{
      margin-left: 10px;
    }
    span:nth-child(1) {
      margin-left: 0;
    }
    .selectBtn{
      position: absolute;
      bottom: 0;
      right: 0;
      color: rgba(0,0,0,0.5);
      cursor: pointer;
    }
  } 
}
</style>
